import 'dart:async';

import 'package:account_book/common/dao/book_dao.dart';
import 'package:account_book/common/dao/base_dao.dart';
import 'package:account_book/common/dao/category_dao.dart';
import 'package:account_book/common/dao/history_dao.dart';
import 'package:get/get.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';


class DatabaseService extends GetxService {

  static DatabaseService get instance => Get.find();
  late Database database;

  final List<BaseDao> _daoList = [
      BookDao.instance,
      CategoryDao.instance,
      HistoryDao.instance,
  ];

  Future<DatabaseService> init() async {
    await initDatabase();
    return this;
  }

  Future<Database> initDatabase() async {
    String databasePath = await getDatabasesPath();
    String path = join(databasePath, "account_book.db");
    database = await openDatabase(path,
        version: 1,
        onCreate: _onCreate,
        onUpgrade: _onUpgrade,
        onDowngrade: _onDowngrade);

    return database;
  }

  Future<Database> open() async {
    try {
      if (database.isOpen) {
        return database;
      } else {
        return await initDatabase();
      }
    } catch (e) {
      return await initDatabase();
    }
  }

  Future<void> close() async {
    return database.close();
  }

  FutureOr<void> _onCreate(Database db, int version) {
    Future.forEach(_daoList, (dao) => dao.onCreate(db, version));
  }

  FutureOr<void> _onDowngrade(Database db, int oldVersion, int newVersion) {
    Future.forEach(_daoList, (dao) => dao.onDowngrade(db, oldVersion, newVersion));
  }

  FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion)  {
    Future.forEach(_daoList, (dao) => dao.onUpgrade(db, oldVersion, newVersion));
  }
}